import Request from 'luch-request'
import authApi from "../utils/auth";
import CommonConfig  from "./config";
// import { ElNotification } from 'element-plus'
const http = new Request();
let notify = null
http.setConfig((config) => {
    config.baseURL = CommonConfig.domain
    config.dataType = 'json'
    config.header = {
        'content-type': 'application/json;charset=UTF-8'
    }
    return config
})

// 请求前拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
    uni.showLoading({ mask: true, title: "加载中" });
    uni.setStorageSync("TABLE_STATUS",true)
    config.header = {
        ...config.header,
    }
    if(config.custom && config.custom.baseURL && config.custom.baseURL.length>0){
        config.baseURL = config.custom.baseURL
    }
    //获取存储的token
    const token = authApi.getToken();
    // config.header.token = token;
    config.header.Authorization = 'Bearer '+token
    config.header.BranchUuid = uni.getStorageSync("branch_uuid")
    console.log("table_no===========>",uni.getStorageSync("table_no"))
	let table_no = uni.getStorageSync("table_no")
	if(!table_no) table_no = ""
    config.header.TableNo = encodeURIComponent(table_no,"UTF-8")
    return config
}, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
})

// 请求后拦截器
http.interceptors.response.use((response) => {
	console.log(response)
    uni.hideLoading();
	if(response.data.code === 401){
        const allPages = getCurrentPages()
        if(allPages[allPages.length-1].route === "pages/login/index"){
            uni.redirectTo({
                url:"/pages/login/index"
            })
        }else {
            uni.navigateTo({
                url:"/pages/login/index"
            })
        }

        uni.showToast({
            icon: "none",
            duration: 3000,
            title: '登陆失败',
        });
	}
	console.log('====>', response)
	if (response.data.code != 200 && response.data.message != '') {
		// if (notify != null) {
		// 	notify.close()
		// 	notify = null
		// }
        // 是否关闭默认打印的标识
        // if(!response.config.custom || !response.config.custom.noPrintMessage){
        //     notify = ElNotification({message: response.data.message, type: 'error', showClose: false, duration: 3000, position: 'bottom-right'})
        // }
        // 餐桌无效
        if(response.data.code === -2){
            uni.setStorageSync("TABLE_STATUS",false)
        }
        // 非成功状态码弹窗
        uni.showToast({
            icon: "none",
            duration: 3000,
            title: response.data.message,
        });
	}
    return response.data
}, (response) => {
	console.log('错误')
    // 未登录时清空缓存跳转
    if(response.statusCode === 401){
        authApi.removeToken();
    }
    return Promise.reject(response)
})

export {http}
